import {Config} from "config.js";

class Token {
    
  constructor(){
    this.tokenUrl = Config.url + 'token/user'
    this.verifyUrl = Config.url + 'token/veirfy'
  }

  verify(){
    var token = wx.getStorageInfoSync('token');
    if(!token){
      this.getTokenFromServer();
    }else{
      this._veirfyFromServer(token); 
    }
  }

// 从服务器获取token
  getTokenFromServer(callBack){
    var that = this;
    wx.login({
      success: function (res) {
        var code = res.code;
        console.log('code');
        console.log(res.code);  
        wx.request({
          url: that.tokenUrl,
          data: {
            code: code
          },
          method: 'POST',
          success: function (res) {
            wx.setStorageSync('token', res.data.data);
            callBack && callBack(res.data.data);
          },
          fail: function (res) {
            // console.log(res.data);
          }
        })
      }
    })
  }


// 去服务器检验令牌
  _veirfyFromServer(token){
    var that = this;
    wx.request({
      url: that.verifyUrl,
      data: {
        token: token
      },
      method: 'POST',
      success: function (res) {
        console.log(res.data);
        var valid = res.data.isValid;
        if (!valid){
          that.getTokenFromServer();  
        }
      }
    })
  }

}
export{Token};